package net.shopxx.action.shop;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import javax.annotation.Resource;
import javax.servlet.jsp.PageContext;

import net.shopxx.bean.Pager;
import net.shopxx.bean.SystemConfig.PointType;
import net.shopxx.bean.SystemConfig.StoreFreezeTime;
import net.shopxx.entity.CartItem;
import net.shopxx.entity.CartItemGroupbuy;
import net.shopxx.entity.CartItemProduct;
import net.shopxx.entity.DeliveryType;
import net.shopxx.entity.Groupbuy;
import net.shopxx.entity.Order;
import net.shopxx.entity.OrderItem;
import net.shopxx.entity.OrderLog;
import net.shopxx.entity.OrderPointer;
import net.shopxx.entity.PaymentConfig;
import net.shopxx.entity.Product;
import net.shopxx.entity.ProductComment;
import net.shopxx.entity.Receiver;
import net.shopxx.entity.Order.OrderStatus;
import net.shopxx.entity.Order.PaymentStatus;
import net.shopxx.entity.Order.ShippingStatus;
import net.shopxx.entity.OrderLog.OrderLogType;
import net.shopxx.entity.Product.WeightUnit;
import net.shopxx.service.AreaService;
import net.shopxx.service.CartItemService;
import net.shopxx.service.DeliveryTypeService;
import net.shopxx.service.HtmlService;
import net.shopxx.service.OrderItemService;
import net.shopxx.service.OrderLogService;
import net.shopxx.service.OrderPointerService;
import net.shopxx.service.OrderService;
import net.shopxx.service.PaymentConfigService;
import net.shopxx.service.ProductCommentService;
import net.shopxx.service.ProductService;
import net.shopxx.service.ReceiverService;
import net.shopxx.util.ArithUtil;
import net.shopxx.util.SystemConfigUtil;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.axiyue.trip.response.TripUtil;
import com.opensymphony.oscache.base.Cache;
import com.opensymphony.oscache.web.ServletCacheAdministrator;
import com.opensymphony.xwork2.interceptor.annotations.InputConfig;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;

/**
 * 前台Action类 - 订单处理
 */

@ParentPackage("member")
@InterceptorRefs({
	@InterceptorRef(value = "token", params = {"excludeMethods", "info,list,view,pointdetail,pointexchange"}),
	@InterceptorRef(value = "memberStack")
})
public class OrderAction extends BaseShopAction {
	
	private static final long serialVersionUID = 2553137844831167917L;
	
	private Boolean isSaveReceiver;// 是否保存收货地址
	private Integer totalQuantity;// 商品总数
	private Integer totalPoint;// 总积分
	private Double totalWeightGram;// 商品总重量（单位：g）
	private BigDecimal productTotalPrice;// 总计商品价格
	private String memo;// 附言
	private String orderStatus;
	private String paymentStatus;
	private String shippingStatus;
	
	
	private Receiver receiver;// 其它收货地址
	private DeliveryType deliveryType;// 配送方式
	private PaymentConfig paymentConfig;// 支付方式
	private Order order;// 订单
	private Set<Order> orders;// 订单
	private Set<CartItem> cartItemSet;// 购物车项
	private List<ProductComment> productCommentSet;

	@Resource
	private ReceiverService receiverService;
	@Resource
	private AreaService areaService;
	@Resource
	private DeliveryTypeService deliveryTypeService;
	@Resource
	private PaymentConfigService paymentConfigService;
	@Resource
	private OrderService orderService;
	@Resource
	private OrderPointerService orderPointerService;
	@Resource
	private OrderLogService orderLogService;
	@Resource
	private CartItemService cartItemService;
	@Resource
	private OrderItemService orderItemService;
	@Resource
	private ProductService productService;
	@Resource
	private HtmlService htmlService;
	@Resource
	private ProductCommentService productCommentService;
	
	public BigDecimal getPostFee()
	{
		return getDeliveryFee(0);
	}
	public BigDecimal getExpressFee()
	{
		return getDeliveryFee(1);
	}
	public BigDecimal getEmsFee()
	{
		return getDeliveryFee(2);
	}
	
	
	public BigDecimal getDeliveryFee(int type) {
		BigDecimal ret = new BigDecimal("0");
		BigDecimal p= null;
		switch(type)
		{
		case 0:
			for (CartItem cartItemTemp : cartItemSet) {
				Product product = null;
				if (cartItemTemp instanceof CartItemProduct) {
					CartItemProduct cartItem = (CartItemProduct) cartItemTemp;
					product = cartItem.getProductitem().getProduct();
				}
				else if(cartItemTemp instanceof CartItemGroupbuy) {
					CartItemGroupbuy cartItem = (CartItemGroupbuy) cartItemTemp;
					product = cartItem.getGroupbuy().getProduct();
				}
				 p=product.getDeliveFee(type, cartItemTemp.getQuantity());
				ret=ret.add(p);
			}
			break;
		case 1:
			for (CartItem cartItemTemp : cartItemSet) {
				Product product = null;
				if (cartItemTemp instanceof CartItemProduct) {
					CartItemProduct cartItem = (CartItemProduct) cartItemTemp;
					product = cartItem.getProductitem().getProduct();
				}
				else if(cartItemTemp instanceof CartItemGroupbuy) {
					CartItemGroupbuy cartItem = (CartItemGroupbuy) cartItemTemp;
					product = cartItem.getGroupbuy().getProduct();
				}

				p=product.getDeliveFee(type, cartItemTemp.getQuantity());
				ret = ret.add(p);
			}
			break;
		case 2:
			for (CartItem cartItemTemp : cartItemSet) {
				Product product = null;
				if (cartItemTemp instanceof CartItemProduct) {
					CartItemProduct cartItem = (CartItemProduct) cartItemTemp;
					product = cartItem.getProductitem().getProduct();
				}
				else if(cartItemTemp instanceof CartItemGroupbuy) {
					CartItemGroupbuy cartItem = (CartItemGroupbuy) cartItemTemp;
					product = cartItem.getGroupbuy().getProduct();
				}
				p=product.getDeliveFee(type, cartItemTemp.getQuantity());
				ret=ret.add(p);
			}
			break;
		default:
			for (CartItem cartItemTemp : cartItemSet) {
				Product product = null;
				if (cartItemTemp instanceof CartItemProduct) {
					CartItemProduct cartItem = (CartItemProduct) cartItemTemp;
					product = cartItem.getProductitem().getProduct();
				}
				else if(cartItemTemp instanceof CartItemGroupbuy) {
					CartItemGroupbuy cartItem = (CartItemGroupbuy) cartItemTemp;
					product = cartItem.getGroupbuy().getProduct();
				}

				p=product.getDeliveFee(type, cartItemTemp.getQuantity());
				ret = ret.add(p);
			}
		}
		return ret;
	}
	

	
	
	public BigDecimal getDeliveryFeeByItems(int type,Set<CartItem> cartItemSet) {
		BigDecimal ret = new BigDecimal("0");
		BigDecimal p= null;
		switch(type)
		{
		case 0:
			for (CartItem cartItemTemp : cartItemSet) {
				Product product = null;
				if (cartItemTemp instanceof CartItemProduct) {
					CartItemProduct cartItem = (CartItemProduct) cartItemTemp;
					product = cartItem.getProductitem().getProduct();
				}
				else if(cartItemTemp instanceof CartItemGroupbuy) {
					CartItemGroupbuy cartItem = (CartItemGroupbuy) cartItemTemp;
					product = cartItem.getGroupbuy().getProduct();
				}
				 p=product.getDeliveFee(type, cartItemTemp.getQuantity());
				ret=ret.add(p);
			}
			break;
		case 1:
			for (CartItem cartItemTemp : cartItemSet) {
				Product product = null;
				if (cartItemTemp instanceof CartItemProduct) {
					CartItemProduct cartItem = (CartItemProduct) cartItemTemp;
					product = cartItem.getProductitem().getProduct();
				}
				else if(cartItemTemp instanceof CartItemGroupbuy) {
					CartItemGroupbuy cartItem = (CartItemGroupbuy) cartItemTemp;
					product = cartItem.getGroupbuy().getProduct();
				}

				p=product.getDeliveFee(type, cartItemTemp.getQuantity());
				ret = ret.add(p);
			}
			break;
		case 2:
			for (CartItem cartItemTemp : cartItemSet) {
				Product product = null;
				if (cartItemTemp instanceof CartItemProduct) {
					CartItemProduct cartItem = (CartItemProduct) cartItemTemp;
					product = cartItem.getProductitem().getProduct();
				}
				else if(cartItemTemp instanceof CartItemGroupbuy) {
					CartItemGroupbuy cartItem = (CartItemGroupbuy) cartItemTemp;
					product = cartItem.getGroupbuy().getProduct();
				}
				p=product.getDeliveFee(type, cartItemTemp.getQuantity());
				ret=ret.add(p);
			}
			break;
		default:
			for (CartItem cartItemTemp : cartItemSet) {
				Product product = null;
				if (cartItemTemp instanceof CartItemProduct) {
					CartItemProduct cartItem = (CartItemProduct) cartItemTemp;
					product = cartItem.getProductitem().getProduct();
				}
				else if(cartItemTemp instanceof CartItemGroupbuy) {
					CartItemGroupbuy cartItem = (CartItemGroupbuy) cartItemTemp;
					product = cartItem.getGroupbuy().getProduct();
				}

				p=product.getDeliveFee(type, cartItemTemp.getQuantity());
				ret = ret.add(p);
			}
		}
		return ret;
	}
	
	// 订单信息
	@InputConfig(resultName = "error")
	public String info() {
		cartItemSet = getLoginMember().getCartItemSet();
		if (cartItemSet == null || cartItemSet.size() == 0) {
			addActionError("购物车目前没有加入任何商品！");
			return ERROR;
		}
		for (CartItem cartItemTemp : cartItemSet) {
			if (cartItemTemp instanceof CartItemProduct) {
				CartItemProduct cartItem = (CartItemProduct) cartItemTemp;
				Product product = cartItem.getProductitem().getProduct();
				if (product.getStore() != null && (cartItem.getQuantity() + product.getFreezeStore()) > product.getStore()) {
					addActionError("商品库存不足，请返回修改！");
					return ERROR;
				}
			}
			else if(cartItemTemp instanceof CartItemGroupbuy) {
				CartItemGroupbuy cartItem = (CartItemGroupbuy) cartItemTemp;
				Groupbuy groupbuy = cartItem.getGroupbuy();
				if (groupbuy.getProduct().getStore() != null && (cartItem.getQuantity() + groupbuy.getProduct().getFreezeStore()) > groupbuy.getProduct().getStore()) {
					addActionError("商品库存不足，请返回修改！");
					return ERROR;
				}
			}
		}
		totalQuantity = 0;
		totalPoint = 0;
		totalWeightGram = 0D;
		productTotalPrice = new BigDecimal("0");
		for (CartItem cartItemTemp : cartItemSet) {
			totalQuantity += cartItemTemp.getQuantity();
			if (cartItemTemp instanceof CartItemProduct) {
				CartItemProduct cartItem = (CartItemProduct) cartItemTemp;
				if (getSystemConfig().getPointType() == PointType.productSet) {
					totalPoint = cartItem.getProductitem().getProduct().getPoint() * cartItem.getQuantity() + totalPoint;
				}
				productTotalPrice = cartItem.getProductitem().getProduct().getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(cartItem.getQuantity().toString())).add(productTotalPrice);
				Product product = cartItem.getProductitem().getProduct();
				Double weightGram = DeliveryType.toWeightGram(product.getWeight(), product.getWeightUnit());
				totalWeightGram = ArithUtil.add(totalWeightGram, ArithUtil.mul(weightGram, cartItem.getQuantity()));
			}
			else if(cartItemTemp instanceof CartItemGroupbuy) {
				CartItemGroupbuy cartItem = (CartItemGroupbuy) cartItemTemp;
				if (getSystemConfig().getPointType() == PointType.productSet) {
					totalPoint = cartItem.getGroupbuy().getProduct().getPoint() * cartItem.getQuantity() + totalPoint;
				}
				productTotalPrice = cartItem.getGroupbuy().getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(cartItem.getQuantity().toString())).add(productTotalPrice);
				Groupbuy groupbuy = cartItem.getGroupbuy();
				Double weightGram = DeliveryType.toWeightGram(groupbuy.getProduct().getWeight(), groupbuy.getProduct().getWeightUnit());
				totalWeightGram = ArithUtil.add(totalWeightGram, ArithUtil.mul(weightGram, cartItem.getQuantity()));
			}
		}
		productTotalPrice = SystemConfigUtil.getOrderScaleBigDecimal(productTotalPrice);
		if (getSystemConfig().getPointType() == PointType.orderAmount) {
			totalPoint = productTotalPrice.multiply(new BigDecimal(getSystemConfig().getPointScale().toString())).setScale(0, RoundingMode.DOWN).intValue();
		}
		getRequest().setAttribute("order", this);
		setResponseNoCache();
		return "info";
	}
	
	// 订单保存
	@Validations(
		requiredStrings = {
			@RequiredStringValidator(fieldName = "deliveryType.id", message = "请选择配送方式！")
		}
	)
	@InputConfig(resultName = "error")
	public String save() {
		cartItemSet = getLoginMember().getCartItemSet();
		if (cartItemSet == null || cartItemSet.size() == 0) {
			addActionError("购物车目前没有加入任何商品！");
			return ERROR;
		}
		if (StringUtils.isNotEmpty(receiver.getId())) {
			receiver = receiverService.load(receiver.getId());
			if (areaService.getAreaString(receiver.getAreaPath()) == null) {
				addActionError("收货地址信息不完整，请补充收货地址信息！");
				redirectionUrl = "receiver!edit.action?id=" + receiver.getId();
				return ERROR;
			}
		} else {
			if (StringUtils.isEmpty(receiver.getName())) {
				addActionError("收货人不允许为空！");
				return ERROR;
			}
			if (StringUtils.isEmpty(receiver.getAreaPath())) {
				addActionError("地区不允许为空！");
				return ERROR;
			}
			if (StringUtils.isEmpty(receiver.getAddress())) {
				addActionError("联系地址不允许为空！");
				return ERROR;
			}
			if (StringUtils.isEmpty(receiver.getZipCode())) {
				addActionError("邮编不允许为空！");
				return ERROR;
			}
			if (StringUtils.isEmpty(receiver.getPhone()) && StringUtils.isEmpty(receiver.getMobile())) {
				addActionError("联系电话、联系手机必须填写其中一项！");
				return ERROR;
			}
			if (!areaService.isAreaPath(receiver.getAreaPath())) {
				addActionError("地区错误！");
				return ERROR;
			}
			if (isSaveReceiver == null) {
				addActionError("是否保存不允许为空！");
				return ERROR;
			}
			if (isSaveReceiver) {
				receiver.setIsDefault(false);
				receiver.setMember(getLoginMember());
				receiverService.save(receiver);
			}
		}
		
		//分组
		Map<String,Set<CartItem>> groupMap = new HashMap<String,Set<CartItem>>();
		for (CartItem cartItemTemp : cartItemSet) {
			if (cartItemTemp instanceof CartItemProduct) {
				CartItemProduct cartItem = (CartItemProduct) cartItemTemp;
				String key = cartItem.getProductitem().getProduct().getMember().getId();
				Set<CartItem> items = groupMap.get(key);
				if(items==null)
				{
					items = new HashSet<CartItem>();
					groupMap.put(key, items);
				}
				items.add(cartItem);
				Product product = cartItem.getProductitem().getProduct();
				if (product.getStore() != null && (cartItem.getQuantity() + product.getFreezeStore() > product.getStore())) {
					addActionError("商品[" + product.getName() + "]库存不足！");
					return ERROR;
				}
			}
			else if (cartItemTemp instanceof CartItemGroupbuy) {
				CartItemGroupbuy cartItem = (CartItemGroupbuy) cartItemTemp;
				String key = cartItem.getGroupbuy().getProduct().getMember().getId();
				Set<CartItem> items = groupMap.get(key);
				if(items==null)
				{
					items = new HashSet<CartItem>();
					groupMap.put(key, items);
				}
				items.add(cartItem);
				Groupbuy groupbuy = cartItem.getGroupbuy();
				if (groupbuy.getProduct().getStore() != null && (cartItem.getQuantity() + groupbuy.getProduct().getFreezeStore() > groupbuy.getProduct().getStore())) {
					addActionError("商品[" + groupbuy.getName() + "]库存不足！");
					return ERROR;
				}
			}
			
		}
		String paymentConfigName = null;
		paymentConfig = paymentConfigService.load(paymentConfig.getId());
		paymentConfigName = paymentConfig.getName();
		orders = new HashSet<Order>();
		String deliveryTypeStr = deliveryType.getId();
		deliveryType = deliveryTypeService.load("402881862b9e7507012b9e7e24540008");
		for (Entry<String,Set<CartItem>> entry : groupMap.entrySet()) {
			Integer totalQuantity=0;
			BigDecimal productTotalPrice = new BigDecimal("0");
			Double totalWeightGram= 0D;
			Set<CartItem> items = entry.getValue();
			for (CartItem cartItemTemp : items) {
				if (cartItemTemp instanceof CartItemProduct) {
					CartItemProduct cartItem = (CartItemProduct) cartItemTemp;
					Product product = cartItem.getProductitem().getProduct();
					totalQuantity += cartItem.getQuantity();
					productTotalPrice = cartItem.getProductitem().getProduct().getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(cartItem.getQuantity().toString())).add(productTotalPrice);
					Double weightGram = DeliveryType.toWeightGram(product.getWeight(), product.getWeightUnit());
					totalWeightGram = ArithUtil.add(totalWeightGram, ArithUtil.mul(weightGram, cartItem.getQuantity()));
				}
				else if (cartItemTemp instanceof CartItemGroupbuy) {
					CartItemGroupbuy cartItem = (CartItemGroupbuy) cartItemTemp;
					totalQuantity += cartItem.getQuantity();
					productTotalPrice = cartItem.getGroupbuy().getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(cartItem.getQuantity().toString())).add(productTotalPrice);
					Double weightGram = DeliveryType.toWeightGram(cartItem.getGroupbuy().getProduct().getWeight(), cartItem.getGroupbuy().getProduct().getWeightUnit());
					totalWeightGram = ArithUtil.add(totalWeightGram, ArithUtil.mul(weightGram, cartItem.getQuantity()));
				}
			}
			
			productTotalPrice = SystemConfigUtil.getOrderScaleBigDecimal(productTotalPrice);
			BigDecimal deliveryFee = getDeliveryFeeByItems(Integer.parseInt(deliveryTypeStr),items);
			BigDecimal paymentFee = null;
			paymentFee = paymentConfig.getPaymentFee(productTotalPrice.add(deliveryFee));
			
			//remove cartItem
			BigDecimal totalAmount = productTotalPrice.add(deliveryFee).add(paymentFee);
			
			Order order = new Order();
			order.setOrderStatus(OrderStatus.unprocessed);
			order.setPaymentStatus(PaymentStatus.unpaid);
			order.setShippingStatus(ShippingStatus.unshipped);
			order.setDeliveryTypeName(deliveryType.getName());
			order.setPaymentConfigName(paymentConfigName);
			order.setProductTotalPrice(productTotalPrice);
			order.setDeliveryFee(deliveryFee);
			order.setPaymentFee(paymentFee);
			order.setTotalAmount(totalAmount);
			order.setPaidAmount(new BigDecimal("0"));
			if (totalWeightGram < 1000) {
				order.setProductWeight(totalWeightGram);
				order.setProductWeightUnit(WeightUnit.g);
			} else if(totalWeightGram >= 1000 && totalWeightGram < 1000000) {
				order.setProductWeight(totalWeightGram / 1000);
				order.setProductWeightUnit(WeightUnit.kg);
			} else if(totalWeightGram >= 1000000) {
				order.setProductWeight(totalWeightGram / 1000000);
				order.setProductWeightUnit(WeightUnit.t);
			}
			order.setProductTotalQuantity(totalQuantity);
			order.setShipName(receiver.getName());
			order.setShipArea(areaService.getAreaString(receiver.getAreaPath()));
			order.setShipAreaPath(receiver.getAreaPath());
			order.setShipAddress(receiver.getAddress());
			order.setShipZipCode(receiver.getZipCode());
			order.setShipPhone(receiver.getPhone());
			order.setShipMobile(receiver.getMobile());
			order.setMemo(memo);
			order.setMember(getLoginMember());
			order.setDeliveryType(deliveryType);
			order.setPaymentConfig(paymentConfig);
			order.setSaler(entry.getKey());
			orderService.save(order);
			
			// 商品项
			for (CartItem cartItemTemp : items) {
				if (cartItemTemp instanceof CartItemProduct) {
					CartItemProduct cartItem = (CartItemProduct) cartItemTemp;
					Product product = cartItem.getProductitem().getProduct();
					OrderItem orderItem = new OrderItem();
					orderItem.setProductSn(product.getProductSn());
					orderItem.setProductName(product.getName());
					orderItem.setProductPrice(product.getPreferentialPrice(getLoginMember()));
					orderItem.setProductQuantity(cartItem.getQuantity());
					orderItem.setDeliveryQuantity(0);
					orderItem.setTotalDeliveryQuantity(0);
					orderItem.setProductHtmlFilePath(product.getHtmlFilePath());
					orderItem.setOrder(order);
//					orderItem.setProduct(product);
					orderItem.setProductitem(cartItem.getProductitem());
					orderItemService.save(orderItem);
				}
				else if (cartItemTemp instanceof CartItemGroupbuy) {
					CartItemGroupbuy cartItem = (CartItemGroupbuy) cartItemTemp;
					Groupbuy groupbuy = cartItem.getGroupbuy();
					OrderItem orderItem = new OrderItem();
					orderItem.setProductSn(groupbuy.getProduct().getProductSn());
					orderItem.setProductName(groupbuy.getProduct().getName());
					orderItem.setProductPrice(groupbuy.getPreferentialPrice(getLoginMember()));
					orderItem.setProductQuantity(cartItem.getQuantity());
					orderItem.setDeliveryQuantity(0);
					orderItem.setTotalDeliveryQuantity(0);
					orderItem.setProductHtmlFilePath(groupbuy.getProduct().getHtmlFilePath());
					orderItem.setOrder(order);
					orderItem.setProduct(cartItem.getGroupbuy().getProduct());
					orderItemService.save(orderItem);
				}
			}
			
			// 库存处理
			if (getSystemConfig().getStoreFreezeTime() == StoreFreezeTime.order) {
				for (CartItem cartItemTemp : items) {
					if (cartItemTemp instanceof CartItemProduct) {
						CartItemProduct cartItem = (CartItemProduct) cartItemTemp;
						Product product = productService.load(cartItem.getProductitem().getProduct().getId());
						if (product.getStore() != null) {
							product.setFreezeStore(product.getFreezeStore() + cartItem.getQuantity());
							productService.update(product);
							if (product.getIsOutOfStock()) {
								flushCache();
								htmlService.productContentBuildHtml(product);
							}
						}
					}
					else if (cartItemTemp instanceof CartItemGroupbuy) {
						CartItemGroupbuy cartItem = (CartItemGroupbuy) cartItemTemp;
						Product product = cartItem.getGroupbuy().getProduct();
						if (product.getStore() != null) {
							product.setFreezeStore(product.getFreezeStore() + cartItem.getQuantity());
							productService.update(product);
							if (product.getIsOutOfStock()) {
								flushCache();
								htmlService.productContentBuildHtml(product);
							}
						}
					}
					
				}
			}
			
			// 订单日志
			OrderLog orderLog = new OrderLog();
			orderLog.setOrderLogType(OrderLogType.create);
			orderLog.setOrderSn(order.getOrderSn());
			orderLog.setOperator(null);
			orderLog.setInfo(null);
			orderLog.setOrder(order);
			orderLogService.save(orderLog);
			orders.add(order);
		}
		
		for (CartItem cartItemTemp : cartItemSet) {
			cartItemService.delete(cartItemTemp);
		}
		setResponseNoCache();
		return "result";
	}
	
	// 订单列表
	public String list() {
		if (pager == null) {
			pager = new Pager();
		}
		
		if(StringUtils.isNotEmpty(orderStatus))
		{
			pager.getWhereClause().put("orderStatus", Enum.valueOf(Order.OrderStatus.class, orderStatus));
		}
		
		if(StringUtils.isNotEmpty(paymentStatus))
		{
			pager.getWhereClause().put("paymentStatus", Enum.valueOf(Order.PaymentStatus.class, paymentStatus));
		}
		
		if(StringUtils.isNotEmpty(shippingStatus))
		{
			pager.getWhereClause().put("shippingStatus", Enum.valueOf(Order.ShippingStatus.class, shippingStatus));
		}
		
		pager = orderService.getOrderPager(getLoginMember(), pager);
		return "list";
	}
	
	// 订单详情
	public String view() {
		order = orderService.load(id);
		System.out.println(order.getDivDetails());
		totalPoint = 0;
		if (getSystemConfig().getPointType() == PointType.productSet) {
			for (OrderItem orderItem : order.getOrderItemSet()) {
				totalPoint = orderItem.getProductitem().getProduct().getPoint() * orderItem.getProductQuantity() + totalPoint;
			}
		} else if (getSystemConfig().getPointType() == PointType.orderAmount) {
			totalPoint = order.getProductTotalPrice().multiply(new BigDecimal(getSystemConfig().getPointScale().toString())).setScale(0, RoundingMode.DOWN).intValue();
		}
		return "view";
	}
	
	public String confirm()
	{
		order = orderService.load(id);
		order.setShippingStatus(ShippingStatus.confirmed);
		orderService.update(order);
		//付款给卖家
		
		
		// 订单日志
		OrderLog orderLog = new OrderLog();
		orderLog.setOrderLogType(OrderLogType.confirmed);
		orderLog.setOrderSn(order.getOrderSn());
		orderLog.setOperator(getLoginMember().getUsername());
		orderLog.setInfo("收货人【"+getLoginMember().getUsername()+"】");
		orderLog.setOrder(order);
		orderLogService.save(orderLog);
		redirectionUrl = "order!view.action?id="+id;
		try {
			getResponse().sendRedirect(redirectionUrl);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public String comment()
	{
		order = orderService.load(id);
		return "comment";
	}
	
	public String saveComment()
	{
		order = orderService.load(id);
		for (ProductComment entity : productCommentSet) {
			entity.setMember(getLoginMember());
			entity.setTitle("买家评论");
			entity.setStatus(true);
			productCommentService.save(entity);
		}
		order.setOrderStatus(OrderStatus.commented);
		orderService.save(order);
		// 订单日志
		OrderLog orderLog = new OrderLog();
		orderLog.setOrderLogType(OrderLogType.completed);
		orderLog.setOrderSn(order.getOrderSn());
		orderLog.setOperator(getLoginMember().getUsername());
		orderLog.setInfo("买家评论");
		orderLog.setOrder(order);
		orderLogService.save(orderLog);
		redirectionUrl = "order!view.action?id="+id;
		try {
			getResponse().sendRedirect(redirectionUrl);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	//积分明细
	public String pointdetail()
	{
		if (pager == null) {
			pager = new Pager();
		}
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Order.class);
		detachedCriteria.add(Restrictions.eq("member", getLoginMember())).add(Restrictions.ge("orderStatus", OrderStatus.processed));
		pager = orderService.findByPager(pager, detachedCriteria);
		return "pointdetail";
	}
	//积分
	public String pointexchange()
	{
		if (pager == null) {
			pager = new Pager();
		}
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(OrderPointer.class);
		detachedCriteria.add(Restrictions.eq("member", getLoginMember()));
		pager = orderPointerService.findByPager(pager, detachedCriteria);
		return "pointexchange";
	}
	
	// 更新页面缓存
	private void flushCache() {
		Cache cache = ServletCacheAdministrator.getInstance(getRequest().getSession().getServletContext()).getCache(getRequest(), PageContext.APPLICATION_SCOPE); 
		cache.flushAll(new Date());
	}
	
	// 获取所有配送方式
	public List<DeliveryType> getAllDeliveryType() {
		return deliveryTypeService.getAll();
	}
	
	// 获取所有支付方式
	public List<PaymentConfig> getAllPaymentConfig() {
		return paymentConfigService.getAll();
	}

	public Boolean getIsSaveReceiver() {
		return isSaveReceiver;
	}

	public void setIsSaveReceiver(Boolean isSaveReceiver) {
		this.isSaveReceiver = isSaveReceiver;
	}

	public Integer getTotalQuantity() {
		return totalQuantity;
	}

	public void setTotalQuantity(Integer totalQuantity) {
		this.totalQuantity = totalQuantity;
	}

	public Integer getTotalPoint() {
		return totalPoint;
	}

	public void setTotalPoint(Integer totalPoint) {
		this.totalPoint = totalPoint;
	}

	public Double getTotalWeightGram() {
		return totalWeightGram;
	}

	public void setTotalWeightGram(Double totalWeightGram) {
		this.totalWeightGram = totalWeightGram;
	}

	public BigDecimal getProductTotalPrice() {
		return productTotalPrice;
	}

	public void setProductTotalPrice(BigDecimal productTotalPrice) {
		this.productTotalPrice = productTotalPrice;
	}

	public String getMemo() {
		return memo;
	}

	public void setMemo(String memo) {
		this.memo = memo;
	}

	public Receiver getReceiver() {
		return receiver;
	}

	public void setReceiver(Receiver receiver) {
		this.receiver = receiver;
	}

	public DeliveryType getDeliveryType() {
		return deliveryType;
	}

	public void setDeliveryType(DeliveryType deliveryType) {
		this.deliveryType = deliveryType;
	}

	public PaymentConfig getPaymentConfig() {
		return paymentConfig;
	}

	public void setPaymentConfig(PaymentConfig paymentConfig) {
		this.paymentConfig = paymentConfig;
	}

	public Order getOrder() {
		return order;
	}

	public void setOrder(Order order) {
		this.order = order;
	}

	public Set<CartItem> getCartItemSet() {
		return cartItemSet;
	}

	public void setCartItemSet(Set<CartItem> cartItemSet) {
		this.cartItemSet = cartItemSet;
	}

	public List<ProductComment> getProductCommentSet() {
		return productCommentSet;
	}

	public void setProductCommentSet(List<ProductComment> productCommentSet) {
		this.productCommentSet = productCommentSet;
	}
	public Set<Order> getOrders() {
		return orders;
	}
	public void setOrders(Set<Order> orders) {
		this.orders = orders;
	}
	public String getOrderStatus() {
		return orderStatus;
	}
	public void setOrderStatus(String orderStatus) {
		this.orderStatus = orderStatus;
	}
	public String getPaymentStatus() {
		return paymentStatus;
	}
	public void setPaymentStatus(String paymentStatus) {
		this.paymentStatus = paymentStatus;
	}
	public String getShippingStatus() {
		return shippingStatus;
	}
	public void setShippingStatus(String shippingStatus) {
		this.shippingStatus = shippingStatus;
	}
	
	
	
	

}